﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.NewPBAuto.IView;
using MINERP.NewPBAuto.Forms;
using MINERP.MODEL.FoundationModel;
using MINERP.BLL.NewPB;
using MINERP.MODEL.NewPinBan;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Diagnostics;
using MINERP.NewPBAuto.com;
using MINERP.ComControls;

namespace MINERP.NewPBAuto.Presenter
{
    class MyPhotoSizeComparer : IEqualityComparer<string>
    {
        #region IEqualityComparer<string> 成员

        public bool Equals(string x, string y)
        {
            string[] xWH = x.Split(new char[] { '*' });
            string[] yWH = y.Split(new char[] { '*' });
            if ((xWH[0] == yWH[0] && xWH[1] == yWH[1]) || (xWH[0] == yWH[1] && xWH[1] == yWH[0]))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        public int GetHashCode(string obj)
        {
            //return obj.GetHashCode();
            return -1;
        }

        #endregion
    }

    public class MainPresenter
    {
        #region private fields

        private IMainView _view;
        private NewPBBLL _bll;

        private List<PhotoInfo_PinBan> _photosList;                                      //存放所有照片的列表，各种过滤前的总照片列表
        private List<PhotoInfo_PinBan> _curShowPhotoList;                                //当前照片列表中列出的照片列表
        private List<PhotoInfo_PinBan> _clearBoxPhotos = new List<PhotoInfo_PinBan>();   //清柜的那些照片,暂时无用
        private List<string> _photoSizeList = new List<string>();                        //存放照片尺寸列表
        private List<PicView> _ListPicView = new List<PicView>();                        //用于存放被拖到大纸上所有的图片集合

        private PicView _multilSelectTPicV;//存入多选后形成的那个大的PICV
        private List<PicView> _mulSelPicVList;//被多选的那些图片的集合


        private bool _isNewPhotoList = false;                       //照片列表是否是新的，即主要是不同的打印机、纸型、纸面决定了照片列表是否是新的
        private float _curWraste = 0;                               //当前浪费率
        private int _curMaxX = 0;                                   //当前最大的X值
        private Point _PicEnablePoint = new Point(-1, -1);          //在拖动释放的那一刻，图片能放到的有效的坐标

        #endregion

        public MainPresenter(IMainView view)
        {
            _view = view;
            _bll = new NewPBBLL();
            IntilView();
            _bll.CurentPrinter = DataTransfer.CurPrinter;
        }

        #region help methods

        private void GetSuitPoint(PicView pv)//得到符合大纸范围的合适的坐标
        {
            Point p = pv.Location;
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (pv.Location.Y < 0)
            {
                p.Y = 0;
            }
            if (p.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                p.Y = DataTransfer.inchBoardHeight - pv.Height;
            }
            if (pv.Right > DataTransfer.inchBoardWidth && pv.Left <= DataTransfer.inchBoardWidth)//判断是否压红线
            {
                p.X = DataTransfer.inchBoardWidth + 10;
                //p.Y = (p.Y < 0)||(p.Y>DataTransfer.inchBoardHeight) ? 10 : p.Y;
            }

            pv.Location = p;
        }

        private bool GetSuitPoint(ref Point p, PicView pv)//得到符合大纸范围的合适的坐标,能否找到合适的位置
        {
            bool result = true;
            if (p.X < 0)
            {
                p.X = 0;
            }
            if (p.Y < 0)
            {
                p.Y = 0;
            }
            if (p.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                if (DataTransfer.inchBoardHeight - pv.Height < 0)
                {
                    return false;
                }
                else
                {
                    p.Y = DataTransfer.inchBoardHeight - pv.Height;
                }
            }

            //if (pv.Right > DataTransfer.inchBoardWidth && pv.Left <= DataTransfer.inchBoardWidth)//判断是否压红线
            //{
            //    p.X = DataTransfer.inchBoardWidth + 10;
            //    p.Y = (p.Y < 0) || (p.Y > DataTransfer.inchBoardHeight) ? 10 : p.Y;
            //}

            return result;
        }

        private void ShowWraste()//显示浪费率
        {
            int effectArea, MaxX, totalArea;//有效面积与最大X值、以及总面积
            float wraste;
            Color wTextColor = Color.Orange;//浪费率的显示颜色

            effectArea = _ListPicView.Where(pv => pv.IsOutRedLine == false).Sum(pv => pv.Width * pv.Height);
            try
            {
                MaxX = _ListPicView.Where(pv => pv.IsOutRedLine == false).Max(pv => pv.Right);
            }
            catch (InvalidOperationException)//ListPicView.Where(pv => pv.IsOutRedLine == false)为空    
            {
                _view.ShowWaste(string.Format("{0:0.00}%", 0), wTextColor);
                return;
            }
            _curMaxX = MaxX;
            totalArea = MaxX * DataTransfer.inchBoardHeight;
            wraste = 1 - ((float)effectArea / (float)totalArea);
            _curWraste = wraste;
            if (wraste > 0.1)
            {
                wTextColor = Color.Red;
            }
            _view.ShowWaste(string.Format("{0:0.00}%", wraste * 100), wTextColor);
        }

        private void BindPhotos(List<PhotoInfo_PinBan> sourcePList)
        {
            _view.BindMainGrid(sourcePList);
            BindShopList(sourcePList);
            BindPhotoSizeList(sourcePList);
        }

        private void BindDefaultPhotos()//默认绑定当前主GRIDVIEW中的照片列表
        {
            _view.BindMainGrid(_curShowPhotoList);
            BindShopList(_curShowPhotoList);
            BindPhotoSizeList(_curShowPhotoList);
        }

        private void BindShopList(List<PhotoInfo_PinBan> sourcePList)  //绑定商户列表
        {
            List<BindShopInfo> listBindShop = new List<BindShopInfo>();
            foreach (var item in sourcePList.GroupBy(p => p.ShopName))
            {
                BindShopInfo shopInfo = new BindShopInfo() { ShopName = item.Key };
                shopInfo.Ctms = new List<BindCtmInfo>();
                foreach (var ctmName in item.Select(p => p.CtmName).Distinct())
                {
                    BindCtmInfo ctmInfo = new BindCtmInfo() { CtmName = ctmName };
                    ctmInfo.OrderProductS = item.Where(p => p.CtmName == ctmName).Select(p => p.OrderInfoName).Distinct().ToList();

                    ctmInfo.OrderList = new List<BindOrderInfo>();
                    foreach (var orderName in ctmInfo.OrderProductS)
                    {
                        ctmInfo.OrderList.Add(new BindOrderInfo()
                        {
                            IsPriority = item.Where(p => p.CtmName == ctmName && p.OrderInfoName == orderName).Max(p => p.Priority) >= 6 || item.Where(p => p.CtmName == ctmName && p.OrderInfoName == orderName && p.IsRebackPhoto).Count() > 0,
                            OrderProductName = orderName
                        });

                    }
                    shopInfo.Ctms.Add(ctmInfo);
                }
                listBindShop.Add(shopInfo);
            }

            _view.BindShopList(listBindShop);
        }

        private void BindPhotoSizeList(List<PhotoInfo_PinBan> sourcePList)  //绑定尺寸列表
        {
            _photoSizeList = sourcePList.Select(p => p.PhotoSize).Distinct(new MyPhotoSizeComparer()).OrderBy(s => Convert.ToSingle(s.Substring(0, s.IndexOf("*")))).ThenBy(s => Convert.ToSingle(s.Substring(s.IndexOf("*") + 1))).ToList();

            _view.BindPhotoSizeList(_photoSizeList);
        }

        //private void GetSuitPhotosByTemplate() //根据当前的模板得到合适的照片列表
        //{
        //    _bll.PBorderNum = DataTransfer.ShowOrderNum;
        //    _photosList = _bll.GetAllPhotos(DataTransfer.CurPrinter.PrinterID, DataTransfer.curTemplate.PaperTypeId, DataTransfer.curTemplate.PaperFaceId);
        //    _curShowPhotoList = _photosList;
        //}
        private void GetSuitPhotosByTemplate(bool showAllPapertypePhotos) //根据当前的模板得到合适的照片列表
        {
            _bll.PBorderNum = DataTransfer.ShowOrderNum;
            _photosList = _bll.GetAllPhotos(DataTransfer.CurPrinter.PrinterID, DataTransfer.curTemplate.PaperTypeId, DataTransfer.curTemplate.PaperFaceId,showAllPapertypePhotos);
            _curShowPhotoList = _photosList;
        }

        private void IntilView()  //初始化界面元素
        {
            FrmSelectPrinter frmSel = new FrmSelectPrinter();

            while (DataTransfer.CurPrinter == null)
            {
                frmSel.ShowDialog();
            }

            ShowStatusMsg();
            _view.InitCtlsLoaction();
            _view.DrawScaleLine();

            //绑定模板列表
            BindTemplate();
        }

        private void ShowStatusMsg()//在状态栏显示Msg主要是操作员、打印机、是否有条码
        {
            string msg = "操作员：" + DataTransfer.curUser + "    | 当前设备：" + DataTransfer.CurPrinter.PName + "   |" + (DataTransfer.curTemplate.HasBarCode == false ? "有条码" : "无条码");
            _view.ShowStatusMsg(msg);
        }

        private void BindTemplate()//绑定模板
        {
            if (DataTransfer.TemplateList == null || DataTransfer.TemplateList.Count < 1)
            {
                DataTransfer.TemplateList = _bll.GetAllTemplate(DataTransfer.CurPrinter.PrinterID);
            }

            _view.BindCmbTempate(DataTransfer.TemplateList);
        }

        private void ResolveAutoPBResult(List<PhotoInfo_PinBan> listResult)//解析自动拼板的结果（主要是用来显示在大纸上）
        {
            foreach (PhotoInfo_PinBan pInfo in listResult)
            {
                //Point screenLoaction = new Point(Convert.ToInt32(((float)pInfo.Location.X / 254) * DataTransfer.perPix), Convert.ToInt32(((float)pInfo.Location.Y / 254) * DataTransfer.perPix));
                Point screenLoaction = new Point(Convert.ToInt32(((float)pInfo.Location.X / DataTransfer.CurPrinter.PDPI) * DataTransfer.perPix), Convert.ToInt32(((float)pInfo.Location.Y / DataTransfer.CurPrinter.PDPI) * DataTransfer.perPix));
                PicView picV = new PicView(pInfo, screenLoaction);
                //if (pInfo.IsWhirl)
                //{
                //    int newWidth, newHeight;
                //    if (DataTransfer.curTemplate.HasBarCode)//有条码
                //    {
                //        newWidth = picV.Height + DataTransfer.BarCodePixWidth;
                //        newHeight = picV.Width - DataTransfer.BarCodePixWidth;
                //    }
                //    else//无条码
                //    {
                //        newWidth = picV.Height;
                //        newHeight = picV.Width;
                //    }

                //    picV.Width = newWidth;
                //    picV.Height = newHeight;
                //    picV.IsWhirl = true;
                //}
                _ListPicView.Add(picV);
                picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
                picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

                picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);

                picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);


                _view.ShowPic(picV);
            }
            ShowWraste();
        }

        #endregion

        private void picV_KeyPress(object sender, KeyPressEventArgs e)//旋转、删除操作
        {
            PicView picCur = (PicView)sender;
            if (e.KeyChar == (int)Keys.Space)//旋转
            {
                #region 旋转方向
                //PicView picCur = (PicView)sender;

                if (picCur.Type == 1)//多选中的temp大图
                {
                    return;
                }
                int newWidth = 0, newHeight = 0;
                PicView tempPic;
                bool isRect;

                //if (DataTransfer.curTemplate.HasBarCode)//有条码
                //{
                if (picCur.PInfo.BarCodeStatus == 1)
                {
                    newWidth = picCur.Height + DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width - DataTransfer.BarCodePixWidth;
                }
                else if (picCur.PInfo.BarCodeStatus == 0)
                {
                    newWidth = picCur.Height - DataTransfer.BarCodePixWidth;
                    newHeight = picCur.Width + DataTransfer.BarCodePixWidth;
                }

            //}
                else//无条码
                {
                    newWidth = picCur.Height;
                    newHeight = picCur.Width;
                }

                tempPic = new PicView(picCur.PInfo.PhotoId, newWidth, newHeight, picCur.Location);
                Point pt = tempPic.Location;
                bool result = GetSuitPoint(ref pt, tempPic);
                if (result == false)
                {
                    tempPic.Dispose();
                    return;
                }
                tempPic.Location = pt;

                isRect = IsInRect(tempPic);
                if (!isRect)
                {
                    picCur.Location = tempPic.Location;
                    picCur.Width = newWidth;
                    picCur.Height = newHeight;
                    picCur.IsWhirl = !picCur.IsWhirl;
                    ShowWraste();
                }
                tempPic.Dispose();
                #endregion
            }
            else if (e.KeyChar == 100 || e.KeyChar == (int)Keys.Delete || e.KeyChar == (int)Keys.D)//删除
            {
                #region 删除选中图片
                //PicView picCur = (PicView)sender;
                if (picCur.Type == 1)//多选删除
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        foreach (var pic in _mulSelPicVList)
                        {
                            PhotoInfo_PinBan pi = _photosList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);
                            if (pi != null)
                            {
                                pi.IsInBoard = false;
                                pi.IsWhirl = false;
                            }
                            _ListPicView.Remove(pic);
                            pic.Dispose();
                        }

                        _mulSelPicVList.Clear();
                        _multilSelectTPicV.Dispose();
                        _multilSelectTPicV = null;
                        picCur.Dispose();
                        _ListPicView.Remove(picCur);
                    }

                }
                else//单选删除
                {
                    PhotoInfo_PinBan pi = _photosList.FirstOrDefault(p => p.PhotoId == picCur.PInfo.PhotoId);
                    if (pi != null)
                    {
                        pi.IsInBoard = false;
                        pi.IsWhirl = false;
                        picCur.Dispose();
                    }
                    _ListPicView.Remove(picCur);
                }
                _view.RefushMainGrid();
                ShowWraste();

                #endregion
            }
            else if (e.KeyChar == (int)Keys.F || e.KeyChar == 102)//将条码在上下部或是左右部切换
            {
                #region 切换条码的方向
                if (picCur.Type == 1)//多选中的temp大图
                {
                    return;
                }
                if (picCur.PInfo.BarCodeStatus != 2)//有条码
                {
                    int newWidth = 0, newHeight = 0, tempBarCodeStatus = picCur.PInfo.BarCodeStatus;
                    PicView tempPic;
                    bool isRect;

                    if (picCur.PInfo.BarCodeStatus == 1)//条码在左右,切换到上下
                    {
                        newWidth = picCur.Width - DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height + DataTransfer.BarCodePixWidth;
                        tempBarCodeStatus = 0;
                    }
                    else//条码在上下,切换到左右
                    {
                        newWidth = picCur.Width + DataTransfer.BarCodePixWidth;
                        newHeight = picCur.Height - DataTransfer.BarCodePixWidth;
                        tempBarCodeStatus = 1;
                    }

                    tempPic = new PicView(picCur.PInfo.PhotoId, newWidth, newHeight, picCur.Location);
                    Point pt = tempPic.Location;
                    bool result = GetSuitPoint(ref pt, tempPic);
                    if (result == false)
                    {
                        tempPic.Dispose();
                        return;
                    }
                    tempPic.Location = pt;
                    isRect = IsInRect(tempPic);

                    if (!isRect)
                    {
                        picCur.Location = tempPic.Location;
                        picCur.Width = newWidth;
                        picCur.Height = newHeight;
                        picCur.PInfo.BarCodeStatus = tempBarCodeStatus;
                        ShowWraste();
                    }
                    tempPic.Dispose();
                }
                #endregion
            }
            else if (e.KeyChar == (int)Keys.T || e.KeyChar == 116)//选中的图片之打印一张图片的条码，其它照片无条码
            {
                #region
                if (picCur.Type == 1)
                {
                    if (_mulSelPicVList != null && _mulSelPicVList.Count > 1)
                    {
                        if (MessageBox.Show("确定要将选中的照片只打印一张条码？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
                        {
                            return;
                        }
                        bool isSet = false;
                        foreach (var pic in _mulSelPicVList)
                        {
                            if (!isSet)
                            {
                                if (pic.PInfo.BarCodeStatus != 2)
                                {
                                    isSet = true;
                                    continue;
                                }
                                else
                                {
                                    continue;
                                }

                            }

                            //OrderInfo_PB_Info oi = _allOrderList.FirstOrDefault(o => o.order_Base_Info.OrderProductId == pic.PInfo.Photo_Base_Info.OrderProductId);
                            //if (oi != null)
                            //{
                            //PhotoInfo_PB pi = oi.PhotoList.FirstOrDefault(p => p.PhotoId == pic.PInfo.PhotoId);

                            //if (pi != null)
                            //{
                            int newWidth = 0, newHeight = 0;
                            if (pic.PInfo.BarCodeStatus == 1)//条码在左右,切换到无条码
                            {
                                newWidth = pic.Width - DataTransfer.BarCodePixWidth;
                                newHeight = pic.Height;

                            }
                            else//条码在上下,切换到无条码
                            {
                                newWidth = pic.Width;
                                newHeight = pic.Height - DataTransfer.BarCodePixWidth;
                            }

                            pic.Width = newWidth;
                            pic.Height = newHeight;
                            pic.PInfo.BarCodeStatus = 2;
                            //}
                            //}
                        }
                    }
                }

                #endregion
            }
        }

        private void _lblPSize_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }

        private void _lblPName_MouseDown(object sender, MouseEventArgs e)
        {
            picV_MouseDown(((Control)sender).Parent, e);
        }


        #region 拖动图片

        [DllImport("user32")]
        public static extern int IntersectRect(ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpDestRect, ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpSrc1Rect, ref DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT lpSrc2Rect);


        void picV_PicMoveEvent(PicView sender, Point newPoint) //移动图片
        {

            Point CurPoint = newPoint;
            Point controlLocation = sender.Parent.PointToClient(CurPoint);//当前PIC控件在PANEL中的location相对坐标位置

            GetSuitPoint(ref controlLocation, sender);

            if (sender.LeftAnchor || sender.RightAnchor)
            {
                controlLocation.X = sender.Left;
            }
            if (sender.UpAnchor || sender.DownAnchor)
            {
                controlLocation.Y = sender.Top;
            }

            PicView _tempPicView = new PicView(sender.PInfo.PhotoId, sender.Width, sender.Height, controlLocation);
            bool result = false;
            List<PicView> overPicList = null;//如果重叠的话，记录重叠的图片集合

            if (!_tempPicView.IsOutRedLine)//红线外的不管
            {
                result = IsInRect(_tempPicView);
            }
            else
            {
                controlLocation = _tempPicView.Location;
            }

            if (result)//如果虚线框与其它图片重叠
            {
                #region //如果虚线框与其它图片重叠

                Point factPoint = sender.Location;//实框的坐标
                DirEmu direction = GetLoctionDirection(controlLocation, factPoint);//虚线框在实框的什么方位
                PicView overPic = null;
                switch (direction)
                {
                    case DirEmu.LeftUp:
                        #region 左上
                        sender.RightAnchor = false;
                        sender.DownAnchor = false;
                        while (factPoint.X - controlLocation.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            //if (sender.LeftAnchor && sender.UpAnchor)
                            //{
                            //    break;//上和左边都靠上了，再往左上移就不动
                            //}
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                                else
                                {
                                    factPoint.X = 0;
                                    sender.LeftAnchor = true;
                                }
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }

                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderByDescending(pv => pv.Bottom).ToList();
                            //bool hasOver = IsInRect(_tempPicView, ListPicView, out overPic);
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.LeftDown:
                        #region 左下

                        sender.RightAnchor = false;
                        sender.UpAnchor = false;

                        while (factPoint.X - controlLocation.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.LeftAnchor)
                            {
                                if (factPoint.X > 0)
                                {
                                    factPoint.X -= 1;
                                }
                            }
                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.inchBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.inchBoardHeight;
                                    sender.DownAnchor = true;
                                }
                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderByDescending(pv => pv.Right).OrderBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.LeftAnchor)
                                {
                                    factPoint.X += 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.RightDown:

                        #region 右下
                        sender.LeftAnchor = false;
                        sender.UpAnchor = false;

                        while (controlLocation.X - factPoint.X > 1 || controlLocation.Y - factPoint.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }

                            if (!sender.DownAnchor)
                            {
                                if (factPoint.Y < DataTransfer.inchBoardHeight)
                                {
                                    factPoint.Y += 1;
                                }
                                else
                                {
                                    factPoint.Y = DataTransfer.inchBoardHeight;
                                    sender.DownAnchor = true;
                                }

                            }
                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).ThenBy(pv => pv.Top).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);


                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.DownAnchor)
                                {
                                    factPoint.Y -= 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);
                                Debug.WriteLine("重叠的照片ID：" + overPic.PInfo.PhotoId);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }
                        }
                        sender.Location = factPoint;
                        #endregion
                        break;
                    case DirEmu.RightUp:

                        #region 右上
                        sender.DownAnchor = false;
                        sender.LeftAnchor = false;

                        while (controlLocation.X - factPoint.X > 1 || factPoint.Y - controlLocation.Y > 1)
                        {
                            if (!sender.RightAnchor)
                            {
                                factPoint.X += 1;
                            }
                            if (!sender.UpAnchor)
                            {
                                if (factPoint.Y > 0)
                                {
                                    factPoint.Y -= 1;
                                }
                                else
                                {
                                    factPoint.Y = 0;
                                    sender.UpAnchor = true;
                                }
                            }

                            _tempPicView.Location = factPoint;
                            overPicList = _ListPicView.OrderBy(pv => pv.Left).OrderByDescending(pv => pv.Bottom).ToList();
                            bool hasOver = IsInRect(_tempPicView, overPicList, out overPic);
                            if (hasOver)
                            {
                                #region 如果有重叠,就先退回到不重叠的状态，再看与重叠图片的位置关系，再决定是左靠还是右靠还是上靠还是下靠
                                if (!sender.RightAnchor)
                                {
                                    factPoint.X -= 1;
                                }
                                if (!sender.UpAnchor)
                                {
                                    factPoint.Y += 1;
                                }
                                _tempPicView.Location = factPoint;

                                DirEmu dire = GetTwoPicVRelativelyDir(_tempPicView, overPic);

                                switch (dire)
                                {
                                    case DirEmu.Left:
                                        sender.LeftAnchor = true;
                                        break;
                                    case DirEmu.Right:
                                        sender.RightAnchor = true;
                                        break;
                                    case DirEmu.Up:
                                        sender.UpAnchor = true;
                                        break;
                                    case DirEmu.Down:
                                        sender.DownAnchor = true;
                                        break;
                                }
                                break;
                                #endregion
                            }

                        }

                        sender.Location = factPoint;
                        #endregion
                        break;
                }

                #endregion
            }
            else
            {
                sender.Location = controlLocation;
                sender.LeftAnchor = false;
                sender.RightAnchor = false;
                sender.UpAnchor = false;
                sender.DownAnchor = false;
            }

            _PicEnablePoint = sender.Location;
        }

        /// <summary>
        /// 得到pv2相对于pv1的相对位置，这二个图都相邻且不相交的，上、下、左、右,pV1是移动的那图片，PV2是与PV1重叠的，即PV1要靠上PV2
        /// Pv1是不与PV2重叠前的最近的那个图形
        /// </summary>
        /// <param name="pv1"></param>
        /// <param name="pv2"></param>
        /// <returns></returns>
        private DirEmu GetTwoPicVRelativelyDir(PicView pv1, PicView pv2)
        {
            if (pv1.Left >= pv2.Right)
            {
                return DirEmu.Left;
            }
            if (pv1.Right <= pv2.Left)
            {
                return DirEmu.Right;
            }
            if (pv1.Top >= pv2.Bottom)
            {
                return DirEmu.Up;
            }
            if (pv1.Bottom <= pv2.Top)
            {
                return DirEmu.Down;
            }
            return 0;
        }


        /// <summary>
        /// 得到p1相对于P2的方位,左上、左下、右上、右下
        /// </summary>
        /// <param name="p1">虚线框的Location</param>
        /// <param name="p2">实框的Location</param>
        /// <returns></returns>
        private DirEmu GetLoctionDirection(Point p1, Point p2)
        {
            if (p1.X <= p2.X)
            {
                if (p1.Y <= p2.Y)
                {
                    return DirEmu.LeftUp;
                }
                else
                {
                    return DirEmu.LeftDown;
                }
            }
            else
            {
                if (p1.Y <= p2.Y)
                {
                    return DirEmu.RightUp;
                }
                else
                {
                    return DirEmu.RightDown;
                }
            }
        }

        /// <summary>
        /// 方向
        /// </summary>
        enum DirEmu
        {
            LeftUp = 1,//左上
            LeftDown = 2,//左下
            RightDown = 3,//右下
            RightUp = 4,//右上

            Left = 5,
            Right,
            Up,
            Down
        }

        #region 是否重叠


        private PicView _RedPicView;//代码红线的矩形框
        /// <summary>
        /// 判断图片是否和tarGetList集合中的有重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="tarGetList"></param>
        /// <param name="overPic">和PV重叠的那张图片</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv, List<PicView> tarGetList, out PicView overPic)
        {
            bool result = false;
            if (pv.IsOverRedLin)
            {
                if (_RedPicView == null)
                {
                    _RedPicView = new PicView(0, 1, DataTransfer.inchBoardHeight, new Point(DataTransfer.inchBoardWidth, 0));
                }
                overPic = _RedPicView;
                //overPic = new PicView(0, 1, DataTransfer.inchBoardHeight, new Point(DataTransfer.inchBoardWidth, 0));
                return true;
            }
            overPic = null;
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT rectResult = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT();//如果相交的话，此值就不为空
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT curtRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(pv.Rect);


            foreach (var picV in tarGetList)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT PicVRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(picV.Rect);
                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    if (res > 0)
                    {
                        result = true;
                        overPic = picV;
                        break;
                    }
                }
            }

            return result;
        }

        /// <summary>
        /// 查看图片是否超出了边界
        /// </summary>
        /// <param name="pv"></param>
        /// <returns></returns>
        private bool IsOverBoard(PicView pv)
        {
            if (pv.Location.X < 0)
            {
                return true;
            }
            if (pv.Location.Y < 0)
            {
                return true;
            }
            if (pv.Location.Y + pv.Height > DataTransfer.inchBoardHeight)
            {
                return true;
            }
            return false;
        }

        /// <summary>
        ///  判断图片是否与其它已存在的图片重叠
        /// </summary>
        /// <param name="pv"></param>
        /// <param name="overPicList">与PV重叠的那些图片集合</param>
        /// <returns></returns>
        public bool IsInRect(PicView pv)
        {
            bool result = false;
            //先得判断是否出拼板区的边界
            if (IsOverBoard(pv))
                return true;

            if (pv.IsOverRedLin)
            {
                return true;
            }

            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT rectResult = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT();//如果相交的话，些值就不为空
            DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT curtRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(pv.Rect);

            foreach (var picV in _ListPicView)
            {
                if (picV.PInfo.PhotoId != pv.PInfo.PhotoId && picV.IsOutRedLine == false && picV.Type != 2)
                {
                    DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT PicVRect = new DevExpress.Utils.Drawing.Helpers.NativeMethods.RECT(picV.Rect);
                    int res = IntersectRect(ref rectResult, ref PicVRect, ref curtRect);
                    if (res > 0)
                    {
                        result = true;
                        break;
                    }
                }
            }

            return result;
        }

        #endregion


        [DllImport("user32.dll")]
        public static extern bool ReleaseCapture();
        [DllImport("user32.dll")]
        public static extern bool SendMessage(IntPtr hwnd, int wMsg, int wParam, int lParam);
        public const int WM_SYSCOMMAND = 0x0112;
        public const int SC_MOVE = 0xF010;
        public const int HTCAPTION = 0x0002;
        void picV_MouseDown(object sender, MouseEventArgs e)//按下左键，准备移动
        {
            if (e.Button == MouseButtons.Left)
            {
                PicView _curPicView;            //当前被选中的要进行移动的图片          
                _curPicView = (PicView)sender;

                if (_curPicView.Type == 0 && _multilSelectTPicV != null)
                {
                    CancelMutilSelect();
                }


                _curPicView.Focus();
                _curPicView.Select();

                //启动移动图片
                ReleaseCapture();
                SendMessage(_curPicView.Handle, WM_SYSCOMMAND, SC_MOVE + HTCAPTION, 0);
                if (_PicEnablePoint.X != -1)
                {
                    _curPicView.Location = _PicEnablePoint;
                }
                _PicEnablePoint = new Point(-1, -1);
                _curPicView.LeftAnchor = false;
                _curPicView.RightAnchor = false;
                _curPicView.UpAnchor = false;
                _curPicView.DownAnchor = false;
                ShowWraste();
            }

        }

        #endregion 移动图片

        #region public methods

        /// <summary>
        /// 已被放了图片的坐标点
        /// </summary>
        //private List<PicView> _OveredPointList = new List<PicView>();
        /// <summary>
        /// 将托动到大板上的图片放到一个最合适的位置
        /// </summary>
        /// <param name="picV"></param>
        private void SetPicAtSuitPostion(PicView picV)
        {
            bool isSuss = false;
            //所有可能的坐标
            List<Point> LocationList = new List<Point>();
            LocationList.Add(new Point(0, 0));
            foreach (var pic in _ListPicView.Where(p => !p.IsOutRedLine).ToList())
            {
                LocationList.Add(pic.Point2);
                LocationList.Add(pic.Point4);
                LocationList.Add(new Point(pic.Point2.X, 0));
                LocationList.Add(new Point(0, pic.Point4.Y));
            }
            LocationList = LocationList.Except(_ListPicView.Where(p => !p.IsOutRedLine).Select(p => p.Location).ToList()).ToList();
            //清除重复
            LocationList = LocationList.Distinct().ToList();
            //排序
            LocationList = LocationList.OrderBy(p => p.X).ThenBy(p => p.Y).ToList();

            foreach (var point in LocationList)
            {
                picV.Location = point;
                if (IsInRect(picV))//如果重叠，就旋转一下再试
                {
                    picV = CircumrotatePic(picV);
                    if (IsInRect(picV))//如果旋转,还是重叠，则应旋转回来，再继续试下一下结点
                    {
                        picV = CircumrotatePic(picV);
                        continue;
                    }
                    else//旋转后不重叠
                    {
                        picV.IsWhirl = true;
                        isSuss = true;
                        break;
                    }
                }
                else//不重叠
                {
                    isSuss = true;
                    break;
                }
            }
            if (!isSuss)//如果全部试完都还没有成功，则将图片放到红线外
            {
                picV.Location = new Point(DataTransfer.inchBoardWidth + 10, 5);
            }

            AddPicToPanel(picV);

        }

        /// <summary>
        /// 将一个图片放到大板上
        /// </summary>
        /// <param name="picV"></param>
        private void AddPicToPanel(PicView picV)
        {
            _ListPicView.Add(picV);

            picV.PInfo.IsInBoard = true;

            picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
            picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
            picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

            picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
            picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);
            _view.ShowPic(picV);
            ShowWraste();
        }

        /// <summary>
        /// 旋转图片
        /// </summary>
        /// <param name="oldPic"></param>
        /// <returns></returns>
        private PicView CircumrotatePic(PicView oldPic)
        {
            //旋转后再试
            int width, height;
            width = oldPic.Width;
            height = oldPic.Height;

            if (DataTransfer.BarCodeStatus == 1)//条码在左右
            {
                width -= DataTransfer.BarCodePixWidth;
                height += DataTransfer.BarCodePixWidth;
            }
            else if (DataTransfer.BarCodeStatus == 0)//条码在上下
            {
                width += DataTransfer.BarCodePixWidth;
                height -= DataTransfer.BarCodePixWidth;
            }

            oldPic.Width = height;
            oldPic.Height = width;

            return oldPic;
        }

        internal void NewDrawPic(List<PhotoInfo_PinBan> photoList, Point mouseFormBigBoardPoint)
        {
            int overPicCount = 1;//一次拖多张图片放到拼板区或时，如果出现重叠，则将图片放到红线右边上时需要有一个减
            //按照高宽大小排倒序
            photoList = photoList.OrderByDescending(p => p.Height).ThenByDescending(p => p.Width).ToList();
            foreach (var pinfo in photoList)
            {
                PicView picV = new PicView(pinfo, mouseFormBigBoardPoint);
                Point tempPoint = picV.Location;
                if (!GetSuitPoint(ref tempPoint, picV))
                {
                    //旋转后再试
                    picV = CircumrotatePic(picV);

                    if (!GetSuitPoint(ref tempPoint, picV))
                    {
                        picV.Dispose();//释放相应的资源
                        MessageBox.Show("此大板不能放下此图片,请另选一模板");
                        return;
                    }
                    else//旋转后OK
                    {
                        picV.IsWhirl = true;
                    }
                }

                picV.Location = tempPoint;
                if (!picV.IsOutRedLine)
                {
                    SetPicAtSuitPostion(picV);
                }
                else
                {
                    AddPicToPanel(picV);
                }
            }

            if (overPicCount > 1)
            {
                //AutoPB_InBoard();
            }
        }

        internal void DrawPic(List<PhotoInfo_PinBan> photoList, Point mouseFormBigBoardPoint)//将拖到大板上的图片将其放到合适的位置
        {
            foreach (var pinfo in photoList)
            {
                PicView picV = new PicView(pinfo, mouseFormBigBoardPoint);
                //GetSuitPoint(picV);
                Point tempPoint = picV.Location;
                if (!GetSuitPoint(ref tempPoint, picV))
                {
                    //旋转后再试
                    int width, height;
                    width = picV.Width;
                    height = picV.Height;

                    if (DataTransfer.curTemplate.HasBarCode)
                    {
                        if (DataTransfer.BarCodeStatus == 1)//条码在左右
                        {
                            width -= DataTransfer.BarCodePixWidth;
                            height += DataTransfer.BarCodePixWidth;
                        }
                        else//条码在上下
                        {
                            width += DataTransfer.BarCodePixWidth;
                            height -= DataTransfer.BarCodePixWidth;
                        }

                    }

                    picV.Width = height;
                    picV.Height = width;

                    if (!GetSuitPoint(ref tempPoint, picV))
                    {
                        MessageBox.Show("此大板不能放下此图片,请另选一模块");
                        return;
                    }
                    else//旋转后OK
                    {
                        picV.IsWhirl = true;
                    }
                }

                picV.Location = tempPoint;
                if (!picV.IsOutRedLine)
                {
                    bool result = IsInRect(picV);
                    if (result)
                    {
                        picV.Location = new Point(DataTransfer.inchBoardWidth + 10, 0);
                    }
                }
                _ListPicView.Add(picV);

                pinfo.IsInBoard = true;

                picV.MouseDown += new System.Windows.Forms.MouseEventHandler(picV_MouseDown);
                picV.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                picV.KeyPress += new KeyPressEventHandler(picV_KeyPress);

                picV._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
                picV._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);
                _view.ShowPic(picV);
                ShowWraste();
            }
        }

        public void SelectedTemplate()//新建纸或是选择一个模板后
        {

            string strTemplateName = DataTransfer.PreSelectTemplateName;
            if (DataTransfer.curTemplate.TemplateName != strTemplateName)
            {
                if (string.IsNullOrEmpty(strTemplateName))
                {
                    System.Windows.Forms.MessageBox.Show("请选择正确的模板！");
                    return;
                }

                Tb_paperTemplate_Info tempTemplate = DataTransfer.TemplateList.FirstOrDefault(pt => pt.TemplateName == strTemplateName);

                if (tempTemplate == null)
                {
                    System.Windows.Forms.MessageBox.Show("请选择正确的模板！");
                    return;
                }
                else
                {
                    ClearBigBoard();
                    if (tempTemplate.PaperFaceId != DataTransfer.curTemplate.PaperFaceId || tempTemplate.PaperTypeId != DataTransfer.curTemplate.PaperTypeId)
                    {
                        //_isNewPhotoList = true;
                        //根据模板绑定照片列表，以及左边的控件
                        DataTransfer.curTemplate = tempTemplate;
                        RushBindPhotos(_view.ShowAllPapertypePhotos);
                    }
                    else
                    {
                        DataTransfer.curTemplate = tempTemplate;
                        //_isNewPhotoList = false;
                    }

                    //DataTransfer.BarCodeStatus = tempTemplate.HasBarCode ? 1 : 2;
                    //纸型、纸面一样，但是尺寸不一样
                    _view.InitCtlsLoaction();
                    _view.DrawScaleLine();
                }
            }
            else
            {
                //_isNewPhotoList = false;
            }
        }

        public void BindClearBoxList() //绑定清柜的列表
        {
            if (_photosList == null)
            {
                return;
            }
            if (_isNewPhotoList)
            {
                _clearBoxPhotos = _photosList.Where(p => p.IsClearBox == 1).ToList();
                //_curShowPhotoList = _photosList.Where(p => p.IsClearBox == 1).ToList();

                _isNewPhotoList = false;
            }
            else
            {
                if (_clearBoxPhotos == null || _clearBoxPhotos.Count < 1)
                {
                    _clearBoxPhotos = _photosList.Where(p => p.IsClearBox == 1).ToList();
                    //_curShowPhotoList = _photosList.Where(p => p.IsClearBox == 1).ToList();
                }
            }
            //_curShowPhotoList = _clearBoxPhotos;
            //BindDefaultPhotos();
            //BindPhotos(_clearBoxPhotos);
            //_view.BindMainGrid(_clearBoxPhotos);
            BindPhotos(_clearBoxPhotos);
        }

        internal void RushBindPhotos(bool showAllPapertypePhotos)//绑定照片到相应的控件中
        {
            RushBindPhotos(true,showAllPapertypePhotos);
        }
        ///// <summary>
        ///// 刷新
        ///// </summary>
        ///// <param name="refush">是否要从数据库取数据，true-是，false-不需要</param>
        //internal void RushBindPhotos(bool refush)
        //{
        //    ClearBigBoard();
        //    if (refush)
        //    {
        //        _isNewPhotoList = true;
        //        GetSuitPhotosByTemplate();
        //    }
        //    //BindPhotos(_photosList);
        //    BindDefaultPhotos();
        //}

       /// <summary>
       /// 刷新照片
       /// </summary>
        /// <param name="refush">是否要从数据库取数据，true-是，false-不需要</param>
        /// <param name="showAllPapertypePhotos">是否显示全部纸型的照片,true-是，false-不需要</param>
        internal void RushBindPhotos(bool refush,bool showAllPapertypePhotos)
        {
            ClearBigBoard();
            if (refush)
            {
                _isNewPhotoList = true;
                GetSuitPhotosByTemplate(showAllPapertypePhotos);
            }
            //BindPhotos(_photosList);
            BindDefaultPhotos();
        }

        internal void ClearBigBoard()//清空大板
        {
            foreach (var picv in _ListPicView)
            {
                PhotoInfo_PinBan piTemp = _photosList.Find(delegate(PhotoInfo_PinBan pi) { if (pi.PhotoId == picv.PInfo.PhotoId)return true; else return false; });
                if (piTemp != null)
                {
                    piTemp.IsInBoard = false;
                    piTemp.IsWhirl = false;
                }
            }
            _ListPicView.Clear();
            _view.ClearBigBoard();
        }

        internal void FilterShop()//筛选商户照片
        {
            string strSelectShopName = _view.SelectShop;
            string strSelectCtmName = _view.SelectCtmName;
            string strSelectOrderProductName = _view.SelectOrderProductName;
            if (!string.IsNullOrEmpty(strSelectShopName))
            {
                if (strSelectShopName.Equals("全部"))
                {
                    _curShowPhotoList = _photosList;
                }
                else
                {
                    _curShowPhotoList = _photosList.Where(p => p.ShopName == strSelectShopName && p.CtmName == (string.IsNullOrEmpty(strSelectCtmName) ? p.CtmName : strSelectCtmName) && p.OrderInfoName == (string.IsNullOrEmpty(strSelectOrderProductName) ? p.OrderInfoName : strSelectOrderProductName)).ToList();
                }
                //_view.BindMainGrid();
                //BindDefaultPhotos();
                _view.BindMainGrid(_curShowPhotoList);
            }
        }

        internal void FilterPhotoSize()//筛选片尺寸
        {
            string strSelectPhotoSize = _view.SelectPhotoSize;
            if (!string.IsNullOrEmpty(strSelectPhotoSize))
            {
                int inx = strSelectPhotoSize.IndexOf("*");
                string strPSTemp = strSelectPhotoSize.Substring(inx + 1) + "*" + strSelectPhotoSize.Substring(0, inx);

                _curShowPhotoList = _photosList.Where(p => p.PhotoSize == strSelectPhotoSize || p.PhotoSize == strPSTemp).ToList();
                //_view.BindMainGrid(_photosList.Where(p => p.PhotoSize == strSelectPhotoSize || p.PhotoSize == strPSTemp).ToList());
                //BindDefaultPhotos();
                _view.BindMainGrid(_curShowPhotoList);
            }
        }

        internal void PintCurBoard()//打印当前大板
        {
            int result = 0;
            float RealBoardLength = 0;//板的真实长度（对应高度（或宽度））
            if (_curMaxX < 1)
            {
                return;
            }
            RealBoardLength = (float)_curMaxX / DataTransfer.perPix;

            PicView tP = _ListPicView.FirstOrDefault(pv => pv.Type == 1);
            if (tP != null)
            {
                MessageBox.Show("有框选图片，请单击空白处，再打印！");
                return;
            }

            List<PhotoInfo_PinBan> effectPi_PinBan = _ListPicView.Where(pv => pv.IsOutRedLine == false && pv.Type != 1).Select(pv => pv.PInfo).ToList();

            if (effectPi_PinBan.Count > 0)
            {
                result = _bll.CreateBoard(effectPi_PinBan, DataTransfer.curTemplate, DataTransfer.CurPrinter, DataTransfer.curUid, _curWraste, RealBoardLength);
                if (result == 1)
                {
                    MessageBox.Show("添加大板信息时出错！");
                }
                else if (result == -2)//加密是出错
                {
                    MessageBox.Show("与服务器连接失败！");
                }
                else if (result == -1)//拼板超出了范围
                {
                    effectPi_PinBan.Clear();//清出LJ
                    RushBindPhotos(true,_view.ShowAllPapertypePhotos);
                    ClearBigBoard();
                }
                else//result=0
                {
                    //1.清除大板上所有的图片，2清空ListPicView,3重新取得_photosList,
                    _photosList = _photosList.Except(effectPi_PinBan).ToList();
                    effectPi_PinBan.Clear();//清出LJ

                    _curShowPhotoList = _photosList;
                    RushBindPhotos(false,_view.ShowAllPapertypePhotos);
                    ClearBigBoard();
                }
            }
        }

        internal void ShowImgChanged()//是否显示图片
        {
            foreach (var pv in _ListPicView)
            {
                pv.IilitialImg();
            }
        }

        internal void SelectTemplate()// 打开选择模板界面
        {
            FrmTemplate frmN = new FrmTemplate();
            DialogResult result = frmN.ShowDialog();
            if (result == DialogResult.OK)
            {
                BindTemplate();
                SelectedTemplate();
            }
        }

        internal void AutoPB()//自动拼板
        {
            if (_curShowPhotoList.Count > 1)
            {
                List<PhotoInfo_PinBan> listResult;
                ClearBigBoard();
                listResult = _bll.AutoPinS(_curShowPhotoList, DataTransfer.curTemplate, DataTransfer.BarCodeStatus);
                if (listResult.Count > 0)
                {
                    ResolveAutoPBResult(listResult);
                }
            }
        }

        internal void FAutoPB()//全自动拼板
        {
            ClearBigBoard();
            FAutoPB frm = new FAutoPB();
            frm.ShowDialog();
            RushBindPhotos(_view.ShowAllPapertypePhotos);
        }

        internal void ClearDataTransferData()//在页面退出时清空缓存的数据
        {

            DataTransfer.CurPrinter = null;
            DataTransfer.curTemplate = null;
            DataTransfer.curUid = 0;
            DataTransfer.curUser = null;
            DataTransfer.IsShowWaste = false;
            DataTransfer.IsShowImg = false;
            DataTransfer.PreSelectTemplateName = null;
            DataTransfer.TemplateList = null;
        }

        internal void ShowConnectionFrm()//Show出通迅对话框
        {
            frmMain frm = ComControls.frmMain.GetInstance(DataTransfer.curUid);
            frm.Show();
        }

        internal void SendToOtherPrinter()//将选中的照片转发给其它打印机
        {
            List<int> PIdList = _view.SelectPhotoIdList;
            if (PIdList.Count < 1)
            {
                return;
            }

            ZFSelectPrinter frmZF = new ZFSelectPrinter();
            if (frmZF.ShowDialog() == DialogResult.OK)
            {
                int result = _bll.ZFPhoto(PIdList, frmZF.SelectedPrinterId);
                if (result != 1)
                {
                    MessageBox.Show("转发失败！");
                }
                else//转化成功，就刷新列表
                {
                    RushBindPhotos(true,_view.ShowAllPapertypePhotos);
                }
            }
        }

        #endregion

        #region 框选图片

        internal void MultiSelectedPic(PicView pv, List<PicView> selectedCtrls)//框选多张图片
        {
            //1.当新的大图PV加入到_ListPicView
            //2.改变被选图片的type=2
            //3.调整被选图片的相对坐标，及所属父容器
            //4.注册相应的事件，如移动，删除、mouseDown事件等
            //5.改变被选图片的相应事件
            _multilSelectTPicV = pv;
            _mulSelPicVList = selectedCtrls;
            Point p;
            pv.MouseDown += new MouseEventHandler(picV_MouseDown);
            pv.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
            pv.KeyPress += new KeyPressEventHandler(picV_KeyPress);


            _ListPicView.Add(pv);


            foreach (var pic in selectedCtrls)
            {

                pic.Type = 2;

                //取消事件
                pic.MouseDown -= new MouseEventHandler(picV_MouseDown);
                pic.PicMoveEvent -= new MyPicViewMoveHandler(picV_PicMoveEvent);
                pic.KeyPress -= new KeyPressEventHandler(picV_KeyPress);
                pic._lblPName.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                pic._lblPSize.MouseDown -= new MouseEventHandler(_lblPSize_MouseDown);


                //加入事件
                pic.MouseDown += new MouseEventHandler(_lblPName_MouseDown);




                p = pic.Location;
                p.Offset(-pv.Location.X, -pv.Location.Y);
                pic.Location = p;
                pv.Controls.Add(pic);
            }
        }

        internal void CancelMutilSelect()//撤消多选
        {
            //删除多选产生的那个Temp图片
            //将被选的小图片改变状态、还原事件、还原坐标

            if (_mulSelPicVList != null && _multilSelectTPicV != null)
            {
                _ListPicView.Remove(_multilSelectTPicV);
                _multilSelectTPicV.Visible = false;

                foreach (var pic in _mulSelPicVList)
                {
                    pic.Location = new Point(pic.Location.X + _multilSelectTPicV.Location.X, pic.Location.Y + _multilSelectTPicV.Location.Y);
                    pic.Type = 0;

                    //      取消事件          
                    pic.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPName.MouseDown -= new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPSize.MouseDown -= new MouseEventHandler(_lblPSize_MouseDown);

                    //添加事件
                    pic.MouseDown += new MouseEventHandler(picV_MouseDown);
                    pic.PicMoveEvent += new MyPicViewMoveHandler(picV_PicMoveEvent);
                    pic.KeyPress += new KeyPressEventHandler(picV_KeyPress);
                    pic._lblPName.MouseDown += new MouseEventHandler(_lblPName_MouseDown);
                    pic._lblPSize.MouseDown += new MouseEventHandler(_lblPSize_MouseDown);


                    _view.ShowPic(pic);
                }

                _multilSelectTPicV.Dispose();
                _multilSelectTPicV = null;
                _mulSelPicVList.Clear();
            }

        }

        #endregion

        internal void AutoSelectedCurGridThreePicToBoard()//自动从当前列表中远定三张照片放到大板上
        {
            if (_ListPicView.Count>0)
            {
                NewDrawPic(_curShowPhotoList.Where(p=>!p.IsInBoard).Take(5).ToList(), new Point(0, 0));
            }
            else
            {
                NewDrawPic(_curShowPhotoList.Where(p => !p.IsInBoard).ToList(), new Point(0, 0));
            }
            _view.RefushMainGrid();
         
        }
    }
}
